package com.yljk.yljkproject.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;

import com.aliyun.aliyunface.api.ZIMFacade;
import com.baidu.mobstat.Config;
import com.baidu.mobstat.StatService;
import com.huawei.agconnect.common.network.AccessNetworkManager;
import com.huawei.agconnect.crash.AGConnectCrash;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.push.EMPushConfig;
import com.yilijk.base.constants.UserInfo;
import com.yilijk.base.crash.CrashHandlerUtils;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yljk.live.common.utils.MediaCountyManager;
import com.yljk.servicemanager.constants.ConfigApi;
import com.yljk.servicemanager.constants.SdkConfigApi;
import com.yljk.yljkproject.MyActivityManager;

import java.util.Iterator;
import java.util.List;

/**
 * 第三方SDK初始化
 */
public class ThreeSDKInitUtils {
    private static ThreeSDKInitUtils utils;
    private boolean isInitialized = false;

    private ThreeSDKInitUtils() {
    }

    public static ThreeSDKInitUtils getInstance() {
        if (utils == null) {
            synchronized (ThreeSDKInitUtils.class) {
                if (utils == null) {
                    utils = new ThreeSDKInitUtils();
                }
            }
        }
        return utils;
    }

    public void init(Application application) {
        setIsInitialized(true);

        try {
            initHuaweiCrashInfo();
        } catch (Throwable throwable) {

        }

        registerActivityListener(application);
        PushUtils.getPushUtils().initRomDevice(application);
        IMInit(application);//IM环信
//        百度统计初始化
        initBaiDu(application);
        //阿里云认证初始化
        ZIMFacade.install(application);

        CrashHandlerUtils.getInstance().init(application, "/Android/data/com.yljk.yljkproject/files/");

        MediaCountyManager.getInstance().launchInit(application);
    }

    public boolean isIsInitialized() {
        return isInitialized;
    }

    public void setIsInitialized(boolean isInitialized) {
        this.isInitialized = isInitialized;
    }

    /**
     * 华为crash统计 键值对信息
     */
    private void initHuaweiCrashInfo() {
        AccessNetworkManager.getInstance().setAccessNetwork(true);
        AGConnectCrash.getInstance().setCustomKey("dominNo", HttpUtils.getUrl());
        AGConnectCrash.getInstance().setCustomKey("channel", com.yilijk.base.utils.DevicesUtils.getChannel());
        AGConnectCrash.getInstance().setCustomKey("deviceBrand", DevicesUtils.getDeviceBrand());
        AGConnectCrash.getInstance().setCustomKey("deviceId", DevicesUtils.getDeviceId());
        AGConnectCrash.getInstance().setCustomKey("deviceName", DevicesUtils.getDeviceName());
//        AGConnectCrash.getInstance().log(Log.WARN, "set warn log.");

        String mobile = SharedPreferencesUtils.getInstance().getString(UserInfo.mobile, null);
        if (!TextUtils.isEmpty(mobile) && mobile.length() > 4) {
            String shortMobile = mobile.substring(mobile.length() - 4);
            AGConnectCrash.getInstance().setUserId(HttpUtils.getUrl() + "*" + DevicesUtils.getDeviceBrand() + "*" + DevicesUtils.getDeviceId() + "*" + shortMobile);
        } else {
            AGConnectCrash.getInstance().setUserId(HttpUtils.getUrl() + "*" + DevicesUtils.getDeviceBrand() + "*" + DevicesUtils.getDeviceId() + "*");
        }
    }

    private void registerActivityListener(Application application) {
        application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onActivityStarted(Activity activity) {
                // TODO Auto-generated method stub
//                    appCount++;
            }

            @Override
            public void onActivityResumed(Activity activity) {
                // TODO Auto-generated method stub
                MyActivityManager.getInstance().setCurrentActivity(activity);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onActivityStopped(Activity activity) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                // TODO Auto-generated method stub
//                    appCount--;
//                    if (appCount == 0) {
//                        Toast.makeText(getApplicationContext(), "慧医天下APP已切入后台，请勿输入账号信息！", Toast.LENGTH_SHORT).show();
//                    }
//                    if (!isAppOnForeground(activity)) {
//                        Toast.makeText(getApplicationContext(), "慧医天下APP已切入后台", Toast.LENGTH_SHORT).show();
//                    }
                ViewInterceptUtil.check(activity);
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                // TODO Auto-generated method stub
            }
        });
    }

    private void IMInit(Application application) {

        EMOptions options = new EMOptions();
        if (ConfigApi.Open.isOpenUnlinePush) {
            EMPushConfig.Builder builder = new EMPushConfig.Builder(application);
            //判断手机
            if (RomUtil.isEmui()) {
                builder.enableHWPush();
            } else if (RomUtil.isMiui()) {
                builder.enableMiPush("2882303761519857784", "5321985739784");
            } else if (RomUtil.isVivo()) {
                builder.enableVivoPush();
            } else if (RomUtil.isOppo()) {
                builder.enableOppoPush("5675b5657ebf4105ab1a192bdf5f85bc", "9ab25a13df854a5bbf4a4ab1e7b8c815");
            } else if (RomUtil.isFlyme()) {

            } else if (RomUtil.is360()) {
            }
            options.setPushConfig(builder.build());
        }
        //       私有化设置
        if (ConfigApi.Open.isRestServer) {
            options.setRestServer(DevicesUtils.isEnvironment() ? SdkConfigApi.Im.test_RestServer : SdkConfigApi.Im.RestServer);//设置私有云rest地址（ip/域名：port）
            options.setIMServer(DevicesUtils.isEnvironment() ? SdkConfigApi.Im.test_Server : SdkConfigApi.Im.Server);//设置私有云IM地址
            options.setImPort(DevicesUtils.isEnvironment() ? SdkConfigApi.Im.test_Port : SdkConfigApi.Im.Port);//设置私有云IM端口号
            options.enableDNSConfig(SdkConfigApi.Im.enableDNSConfig);//默认是true，在私有云下，需要关闭（设置成false）
            options.setAppKey(DevicesUtils.isEnvironment() ? SdkConfigApi.Im.test_key1 : SdkConfigApi.Im.key);
        } else {
            options.setAppKey(DevicesUtils.isEnvironment() ? SdkConfigApi.Im.test_Key : SdkConfigApi.Im.key);
        }

// 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);
// 是否自动将消息附件上传到环信服务器，默认为True是使用环信服务器上传下载，如果设为 false，需要开发者自己处理附件消息的上传和下载
        options.setAutoTransferMessageAttachments(true);
// 是否自动下载附件类消息的缩略图等，默认为 true 这里和上边这个参数相关联
        options.setAutoDownloadThumbnail(true);
        //自动登录
        options.setAutoLogin(false);
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(application, pid);
// 如果APP启用了远程的service，此application:onCreate会被调用2次
// 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
// 默认的APP会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就立即返回

        if (processAppName == null || !processAppName.equalsIgnoreCase(application.getPackageName())) {
//            Log.e(TAG, "enter the service process!");
            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }
//初始化
        EMClient.getInstance().init(application, options);
//在做打包混淆时，关闭debug模式，避免消耗不必要的资源
        EMClient.getInstance().setDebugMode(DevicesUtils.isEnvironment());
        EMClient.getInstance().getOptions().setRequireDeliveryAck(true);
        //IM环信推送
//        EMPushConfig.Builder builder = new EMPushConfig.Builder(context);
//        builder.enableVivoPush() // 推送证书相关信息配置在AndroidManifest.xml中
//                .enableMeiZuPush("", "")
//                .enableMiPush("", "")
//                .enableOppoPush("", "")
//                .enableHWPush() //开发者需要调用该方法来开启华为推送
//                .enableFCM(""); //开发者需要调用该方法来开启FCM推送
//
//        EMOptions options = new EMOptions();
//        options.setPushConfig(builder.build());

    }


    //IMChat
    private String getAppName(Application application, int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) application.getSystemService(application.ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = application.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // ALog.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    private void initBaiDu(Application application) {
        // 通过该接口可以控制敏感数据采集，true表示可以采集，false表示不可以采集，
        // 建议有用户隐私策略弹窗的App，用户未同意前设置false,同意之后设置true

        String token = SharedPreferencesUtils.getInstance().getString(UserInfo.token, null);
        if (!TextUtils.isEmpty(token)) {
            StatService.setAuthorizedState(application, true);
        }else {
            StatService.setAuthorizedState(application, false);
        }
    }


}
